from django.contrib import admin
from django.utils.translation import gettext_lazy as _
from .models import Project, ProjectMember, ProjectTag, Webhook
import uuid

class ProjectMemberInline(admin.TabularInline):
    """项目成员内联管理"""
    model = ProjectMember
    extra = 1
    fields = ('user', 'role', 'joined_at')
    readonly_fields = ('joined_at',)
    
class ProjectTagInline(admin.TabularInline):
    """项目标签内联管理"""
    model = ProjectTag
    extra = 1
    fields = ('name', 'color')

@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
    """项目空间管理界面"""
    list_display = ('name', 'created_by', 'created_at', 'updated_at')
    search_fields = ('name', 'description')
    list_filter = ('created_by', 'created_at')
    date_hierarchy = 'created_at'
    readonly_fields = ('created_at', 'updated_at')
    inlines = [ProjectMemberInline, ProjectTagInline]
    fieldsets = (
        (None, {'fields': ('name', 'description')}),
        (_('创建信息'), {'fields': ('created_by', 'created_at', 'updated_at')}),
    )
    
    def save_model(self, request, obj, form, change):
        """保存项目时，如果是新建项目，设置创建者为当前用户"""
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)
        
    # 在保存后确保创建者自动成为项目的管理员
    def save_related(self, request, form, formsets, change):
        super().save_related(request, form, formsets, change)
        # 检查是否是新建项目
        if not change:
            project = form.instance
            # 检查创建者是否已经是项目成员
            if not project.members.filter(user=request.user).exists():
                ProjectMember.objects.create(
                    project=project,
                    user=request.user,
                    role='admin'
                )

@admin.register(ProjectMember)
class ProjectMemberAdmin(admin.ModelAdmin):
    """项目成员管理界面"""
    list_display = ('user', 'project', 'role', 'joined_at')
    search_fields = ('user__username', 'project__name')
    list_filter = ('role', 'project')
    readonly_fields = ('joined_at',)

@admin.register(ProjectTag)
class ProjectTagAdmin(admin.ModelAdmin):
    """项目标签管理界面"""
    list_display = ('name', 'color', 'project')
    search_fields = ('name', 'project__name')
    list_filter = ('project',)


from django.utils.html import format_html

@admin.register(Webhook)
class WebhookAdmin(admin.ModelAdmin):
    """项目Webhook管理界面"""
    list_display = ('name', 'project', 'full_url', 'is_active', 'created_at', 'last_triggered_at')
    search_fields = ('name', 'url', 'project__name')
    list_filter = ('is_active', 'project', 'created_at')
    readonly_fields = ('created_at', 'updated_at', 'last_triggered_at')
    fieldsets = (
        (None, {'fields': ('name', 'project', 'url', 'secret', 'is_active')}),
        (_('触发事件'), {'fields': ('events',)}),
        (_('时间信息'), {'fields': ('created_at', 'updated_at', 'last_triggered_at')}),
    )
    
    def full_url(self, obj):
        """显示完整的Webhook URL"""
        return format_html('<div style="word-break: break-all; max-width: 400px;">{}</div>', obj.url)
    
    full_url.short_description = 'URL'
    full_url.admin_order_field = 'url'
    
    def get_form(self, request, obj=None, **kwargs):
        """获取表单时，添加帮助文本并自动生成URL"""
        # 获取表单类而不是表单实例
        FormClass = super().get_form(request, obj, **kwargs)
        
        # 创建一个自定义的表单类来添加我们的自定义行为
        class CustomWebhookForm(FormClass):
            class Media:
                js = ('admin/js/webhook_url_generator.js',)
            
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                
                # 如果是新建Webhook
                if not obj:
                    # 获取URL字段
                    url_field = self.fields.get('url')
                    
                    if url_field:
                        # 为URL字段添加一个初始值，使用网站的实际域名
                        import uuid
                        from django.conf import settings
                        base_url = settings.SITE_DOMAIN
                        example_webhook_id = str(uuid.uuid4())[:12]
                        example_url = f"{base_url}/webhooks/example-project/{example_webhook_id}/receive"
                        
                        # 设置初始值
                        self.initial['url'] = example_url
                        
                        # 添加帮助文本
                        url_field.help_text = _('系统已为您生成一个示例URL，您可以点击"生成URL"按钮重新生成，或手动修改它。')
                        
                        # 添加自定义属性，用于在JavaScript中识别这个字段
                        self.fields['url'].widget.attrs['data-can-generate'] = 'true'
        
        # 返回自定义的表单类
        return CustomWebhookForm
    
    def formfield_for_dbfield(self, db_field, request, **kwargs):
        """自定义字段渲染"""
        field = super().formfield_for_dbfield(db_field, request, **kwargs)
        
        # 为URL字段添加生成按钮
        if db_field.name == 'url' and 'instance' not in kwargs:
            # 添加一个自定义属性，用于在JavaScript中识别这个字段
            if hasattr(field.widget, 'attrs'):
                field.widget.attrs['data-can-generate'] = 'true'
        
        return field
    
    def save_model(self, request, obj, form, change):
        """保存Webhook时，如果是新建且URL为空，自动生成URL"""
        # 如果是新建Webhook且URL为空，自动生成URL
        if not change and not obj.url:
            # 生成基于项目名称和UUID的唯一标识符
            project_slug = obj.project.name.lower().replace(' ', '-')[:20]
            webhook_id = str(uuid.uuid4())[:12]  # 取UUID的前12位作为标识
            
            # 生成更有意义的URL格式，使用网站的实际域名
            from django.conf import settings
            base_url = settings.SITE_DOMAIN
            obj.url = f"{base_url}/webhooks/{project_slug}/{webhook_id}/receive"
        
        super().save_model(request, obj, form, change)
